import 'dart:async';
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_weather_bg/bg/weather_bg.dart';
import 'package:wk_weather/bean/EnventChangeBean.dart';
import 'package:wk_weather/bean/CityInfo.dart';
import 'package:wk_weather/myConfig/weather_type.dart';
import 'package:wk_weather/utils/LocationUtil.dart';
import 'package:wk_weather/utils/SharedPreferenceTool.dart';
import 'package:wk_weather/generated/json/mybean/WeatherModel.dart';
import 'package:flutter_weather_bg/utils/WeatherUtil.dart';
import '../MyApp.dart';


class WeatherMainBg extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _WeatherMainBgState();
  }
}

class _WeatherMainBgState extends State<WeatherMainBg>
    with SingleTickerProviderStateMixin {
  int _index = 0;
  StreamSubscription _subscription;
  List<WeatherType> _weatherTypes;

  @override
  void initState() {
    _subscription = eventBus.on().listen((event) {
      if (event is ChangeMainAppBarIndexEvent) {
        _index = event.index;
        setState(() {});
      }

      else if (event is MainBgChangeEvent) {
        fetchWeatherTypes(); // 接收到有改变时 重新获取
      }
    });

    fetchWeatherTypes(); // 初始化
    super.initState();
  }


  @override
  Widget build(BuildContext context) {
    var width = MediaQuery.of(context).size.width;
    var height = MediaQuery.of(context).size.height;
    WeatherType weatherType = WeatherType.sunny;

    if (_weatherTypes != null && _weatherTypes.isNotEmpty) {
      weatherType = _weatherTypes[_index];
    }

    return Container(
      child: Stack(
        children: [
          WeatherBg(
            weatherType: weatherType,
            width: width,
            height: height,
          ),
        ],
      ),
    );
  }

  @override
  void dispose() {
    _subscription.cancel();
    super.dispose();
  }

  // 获取每个城市对应的天气类型
  Future<void> fetchWeatherTypes() async {
    List<WeatherType> weatherTypes = [];
    List<CityModel> cityModels = await SharedPreferenceTool.getCityModels();
    Map<String, String> allWeatherData = await SharedPreferenceTool.getAllWeatherModels();

    if (cityModels != null && cityModels.isNotEmpty && allWeatherData != null &&allWeatherData.isNotEmpty) {

      cityModels.forEach((element) {
        String key = "${LocationUtil.convertCityFlag(element.cityFlag, element.isLocated)}";
        if (allWeatherData.containsKey(key)) {
          WeatherType weatherType = WeatherType.sunny;
          var modelStr = allWeatherData[key];

          if (modelStr != null && modelStr.isNotEmpty) {
            // json.decode(modelStr)
            // Parses the string and returns the resulting Json object

            //  json obj 转对象
            WeatherModelEntity weatherModelEntity = WeatherModelEntity().fromJson(json.decode(modelStr));

            if (weatherModelEntity != null && weatherModelEntity.result != null &&
                weatherModelEntity.result.realtime != null) {
              weatherType = WeatherUtils.convertWeatherType(weatherModelEntity.result.realtime.skycon);
            }
          }
          weatherTypes.add(weatherType);
        }
      });
    }

    if (weatherTypes.isNotEmpty) {
      setState(() {
        _weatherTypes = weatherTypes;
        _index = _index >= _weatherTypes.length ?   _weatherTypes.length - 1 : _index ;
      });
    }
  }

}
